package com.youmingxing.view.clipheadphoto.clip1.msg;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MessageCenter {

	private static MessageCenter mInst;
	private Map<String, List<MessageListenerDelegate>> listenerDic;

	public static MessageCenter getInstance() {
		if (mInst == null) {
			mInst = new MessageCenter();
		}
		return mInst;
	}

	MessageCenter() {
		this.listenerDic = new HashMap<String, List<MessageListenerDelegate>>();
	}

	public Map<String, List<MessageListenerDelegate>> getListenerDic() {
		return this.listenerDic;
	}

	public void setListenerDic(Map<String, List<MessageListenerDelegate>> map) {
		this.listenerDic = map;
	}

	public void registerListener(MessageListenerDelegate listener, String message_id) {
		if (listener == null) {
			return;
		}
		List<MessageListenerDelegate> listener_arr = this.listenerDic.get(message_id);
		if (listener_arr == null) {
			listener_arr = new ArrayList<MessageListenerDelegate>();
			listenerDic.put(message_id, listener_arr);
		}
		for (int i = 0; i < listener_arr.size(); i++) {
			MessageListenerDelegate exist_listener = listener_arr.get(i);
			if (exist_listener == listener) {
				return;
			}
		}
		listener_arr.add(listener);
	}

	public void removeListener(MessageListenerDelegate listener) {
		Set<String> key_set = ((Set<String>) listenerDic.keySet());
		Iterator<String> i = key_set.iterator();
		while (i.hasNext()) {
			String key = (String) i.next();
			List<MessageListenerDelegate> listener_arr = this.listenerDic.get(key);
			if (listener_arr != null) {
				listener_arr.remove(listener);
			}
		}
	}

	public void removeListenerFromMessage(MessageListenerDelegate listener, String message_id) {
		List<MessageListenerDelegate> listener_arr = this.listenerDic.get(message_id);
		if (listener_arr != null) {
			listener_arr.remove(listener);
		}
	}

	public void sendMessage(BaseMessage message) {
		if (message == null) {
			return;
		}
		List<MessageListenerDelegate> listener_arr = this.listenerDic.get(message.getMsgId());
		if (listener_arr == null) {
			return;
		}
		MessageListenerDelegate listener;
		for (int i = 0; i < listener_arr.size(); i++) {
			listener = listener_arr.get(i);
			listener.getMessage(message);
		}
	}
}
